package com.jeecg.p3.system.poster.web;

import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.base.util.WxUserInfo;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.poster.entity.AdvisorCoupon;
import com.jeecg.p3.system.poster.entity.CustomerCoupon;
import com.jeecg.p3.system.poster.service.AdvisorCouponService;
import com.jeecg.p3.system.poster.service.CustomerCouponService;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @ClassName: CustomerCouponController
 * @Description: TODO 顾客优惠券控制层
 * @author: zhangxiao
 * @date: 2020年12月8日 下午7:29:38
 */
@Controller
@RequestMapping("/system/back/poster/cusCoupon")
public class CustomerCouponController extends BaseController {
    public final Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private CustomerCouponService service;
    @Autowired
    private StudyAdvService studyAdvService;
    @Autowired
    private AdvisorCouponService advisorCouponService;

    /**
     *
     * @param query 顾客优惠券查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/list.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void toIndividual(@ModelAttribute CustomerCoupon query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<CustomerCoupon> pageQuery = new PageQuery<CustomerCoupon>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        Boolean isAdmin = isAdmin(request);
        if(isMobile(request)) {
            String viewName = "system/back/poster/h5_customer_coupon.html";
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            if(!isAdmin) {
                query.setCreateUser(getCurrentUser(request).getId());
            }
            pageQuery.setQuery(query);
            velocityContext.put("customerCoupon",query);
            velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
            String viewName = "system/back/poster/customer_coupon.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    /**
     * 查询顾客待使用优惠券
     * @param query
     * @param request
     * @param response
     * @param pageNo
     * @param pageSize
     * @throws Exception
     */
    @RequestMapping(value="/todoList.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void todoList(@ModelAttribute CustomerCoupon query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<CustomerCoupon> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        Boolean isAdmin = isAdmin(request);

        if(isMobile(request)) {
            String viewName = "system/back/poster/h5_customer_coupon_todo.html";
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            if(!isAdmin) {
                query.setCreateUser(getCurrentUser(request).getId());
            }
            query.setUseStatus("0");
            pageQuery.setQuery(query);
            velocityContext.put("customerCoupon",query);
            velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
            String viewName = "system/back/poster/customer_coupon_todo.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    /**
     * 顾客已使用优惠券
     * @param query
     * @param request
     * @param response
     * @param pageNo
     * @param pageSize
     * @throws Exception
     */
    @RequestMapping(value="/useList.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void useList(@ModelAttribute CustomerCoupon query, HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                         @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<CustomerCoupon> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        Boolean isAdmin = isAdmin(request);

        if(isMobile(request)) {
            String viewName = "system/back/poster/h5_customer_coupon_use.html";
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            if(!isAdmin) {
                query.setCreateUser(getCurrentUser(request).getId());
            }
            query.setUseStatus("1");
            pageQuery.setQuery(query);
            velocityContext.put("customerCoupon",query);
            velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
            String viewName = "system/back/poster/customer_coupon_use.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    /**
     * 手动开通优惠券列表
     * @param query
     * @param request
     * @param response
     * @param pageNo
     * @param pageSize
     * @throws Exception
     */
    @RequestMapping(value="/manualUseList.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void manualUseList(@ModelAttribute CustomerCoupon query, HttpServletRequest request, HttpServletResponse response,
                        @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                        @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<CustomerCoupon> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        Boolean isAdmin = isAdmin(request);
        if(isMobile(request)) {
            String viewName = "system/back/poster/h5_customer_coupon_use.html";
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            if(!isAdmin) {
                query.setCreateUser(getCurrentUser(request).getId());
            }
            query.setOpenType("2");
            query.setUseStatus("1");
            pageQuery.setQuery(query);
            velocityContext.put("customerCoupon",query);
            velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
            String viewName = "system/back/poster/customer_coupon_manual.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    @RequestMapping(value="/toMyList",method = {RequestMethod.GET,RequestMethod.POST})
    public void toMyList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/app/my_get_coupon.html";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     *
     * @param query 顾客优惠券查询对象
     * @param request
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value="/myList",method = {RequestMethod.GET,RequestMethod.POST})
    public Map<String, Object> myList(@ModelAttribute CustomerCoupon query, HttpServletRequest request,
                                      @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                                      @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        LoginUser user = getCurrentUser(request);
        Map<String, Object> map = new HashMap<>();
        PageQuery<CustomerCoupon> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        if(!isAdmin(request)) {
            StudyAdviser adviser = studyAdvService.findByUserNumber(user.getUserId());
            query.setAdvisorId(adviser.getId());
        }
        query.setUseStatus("0");
        pageQuery.setQuery(query);
        map.put("pageInfos", service.queryPageList(pageQuery));
        return map;
    }

    /**
     * 保存信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson doAdd(@ModelAttribute CustomerCoupon customerCoupon, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            WxUserInfo wxUserInfo = getWxUserInfo(request);
            if(wxUserInfo == null) {
                j.setSuccess(false);
                j.setMsg("请微信授权后在进行操作！");
                return j;
            }
            AdvisorCoupon advisorCoupon = advisorCouponService.findById(Long.valueOf(customerCoupon.getAdvCouponId()));
            customerCoupon.setWxOpenId(wxUserInfo.getOpenid());
            customerCoupon.setProductCouponId(advisorCoupon.getProductCouponId());
            List<CustomerCoupon> list = service.findByParam(customerCoupon);
            if(list.size() > 0) {
                j.setSuccess(false);
                j.setMsg("该用户已经领取过该课程优惠券！");
                return j;
            }
            customerCoupon.setWxNickName(wxUserInfo.getNickname());
            customerCoupon.setWxPhoto(wxUserInfo.getHeadimgurl());
            customerCoupon.setCreateDate(DateUtil.dateToString(new Date()));
            customerCoupon.setCreateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            customerCoupon.setUseStatus("0");
            customerCoupon.setStatus("1");
            service.doAdd(customerCoupon);
            j.setMsg("保存成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }

    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping(value="/toEdit",method = RequestMethod.GET)
    public void toEdit(@RequestParam(required = true, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        CustomerCoupon customerCoupon = service.findById(id);
        velocityContext.put("customerCoupon", customerCoupon);
        String viewName = "system/back/poster/customer_coupon_edit.vm";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存修改数据
     * @return
     */
    @RequestMapping(value = "/doEdit",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute CustomerCoupon customerCoupon, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            List<CustomerCoupon> list = service.findByParam(customerCoupon);
            LoginUser user = getCurrentUser(request);
            if(list.size() > 0) {
                j.setSuccess(false);
                j.setMsg("该顾问已经分配过该课程优惠券！");
                return j;
            }
            customerCoupon.setUpdateDate(DateUtil.dateToString(new Date()));
            customerCoupon.setUpdateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            customerCoupon.setUpdateUser(user.getId());
            this.service.doEdit(customerCoupon);
            j.setMsg("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("编辑失败");
        }
        return j;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value="/doDelete",method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson doDelete(@RequestParam(required = true, value = "id" ) Long id, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            CustomerCoupon customerCoupon = service.findById(id);
            customerCoupon.setDeleteDate(DateUtil.dateToString(new Date()));
            customerCoupon.setDeleteTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            customerCoupon.setDeleteUser(user.getId());
            service.doDelete(customerCoupon);
            j.setMsg("删除成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("删除失败:"+e.getMessage());
        }
        return j;
    }
}
